package com.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.Intercepter.UserHolder;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mogo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 今日佳人
     * @return
     */
    public TodayBest todayBest() {
        Long to_user_id = UserHolder.getId();
        RecommendUser recommendUser = recommendUserApi.TodayBest(to_user_id);
        if(recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        Long userId = recommendUser.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        return  vo;
    }

    /**
     * 好友推荐
     * @param dto
     * @return
     */
    public PageResult recommendation(RecommendUserDto dto) {
        Long to_user_id = UserHolder.getId();
        //查询分页相关数据
        PageResult  pr = recommendUserApi.recommendation(dto.getPage(),dto.getPagesize(),to_user_id);
        //获取分页中的列表数据
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if (items.isEmpty() || items.size()<=0){
            return pr;
        }
        //将查询到的推荐的人的id存入集合
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //添加筛选条件
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        Map<Long,UserInfo> map = userInfoApi.MakeFriends(userIds,userInfo);
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser recommendUser : items) {
            UserInfo info = map.get(recommendUser.getUserId());
            if (info!=null){
                TodayBest vo = TodayBest.init(info, recommendUser);
                list.add(vo);
            }
        }
        pr.setItems(list);
        return pr;
    }
}
